<template>
  <div>
    <el-button
      type="primary"
      icon="el-icon-plus"
      @click="openDialog"
      style="margin: 10px 0"
      >添加</el-button
    >
    <!-- 

           label="label" 表格名称
            type=index 序号
             align="center" 居中
             prop = 展示的对应列 字段名
       -->
    <el-table :data="list" style="width: 80%" border>
      <el-table-column
        prop="prop"
        label="序号"
        type="index"
        align="center"
        width="100px"
      >
      </el-table-column>
      <el-table-column prop="tmName" label="品牌名称" width="width">
      </el-table-column>
      <el-table-column prop="prop" label="品牌LOGO" width="width">
        <template slot-scope="{ row, $index }">
          <!--  row 当前列数据 $index 下标 -->
          <img :src="row.logoUrl" alt="" style="width: 100px; height: 100px" />
        </template>
      </el-table-column>
      <el-table-column prop="prop" label="操作" width="width">
        <template slot-scope="{ row, $index }">
          <el-button type="warning" size="small" @click="update(row)"
            >修改</el-button
          >
          <el-button type="danger" size="small" @click="deleteBrand(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 
        :page-size="pageSize" 每页显示 条目个数
        :current-page="pageNum" 当前页数
        :total="totalCount" // 总条数
        pager-count="9" 间隔数 奇数  >=7
        :page-sizes="[10, 20, 50]" 每页显示个数选择器
          layout="total, sizes, prev, pager, next, jumper"  可以改变顺序 改变位置
                 @size-change="handleSizeChange" //改变每页的条数
        @current-change="handleCurrentChange" // 改变页码数
      -->
    <el-pagination
      style="margin-top: 20px; textalign: center"
      :current-page="page"
      :page-sizes="[3, 5, 10]"
      :pager-count="9"
      :page-size="limit"
      layout=" prev, pager, next, jumper,->,total, sizes"
      :total="total"
      @current-change="getPageList"
      @size-change="handleCurrentChange"
    >
    </el-pagination>
    <!-- 弹层
        :rules="rules" 表单验证规则 
       -->
    <el-dialog title="添加品牌" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-form-item label="活动名称" label-width="100px" prop="tmName">
          <el-input v-model="form.tmName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="上传图片" label-width="100px" prop="logoUrl">
          <!-- POST /admin/product/fileUpload-->
          <el-upload
            class="avatar-uploader"
            action="/dev-api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.logoUrl" :src="form.logoUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="cofirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Brand",
  props: {},
  components: {},
  data() {
    // 自定义表单验证规则
    const validatetmName = (rule, value, callback) => {
      if (value.length < 2 || value.length > 10) {
        return callback(new Error("字符限制为2到10位"));
      } else {
        callback();
      }
    };
    return {
      // 分页器的第几页
      page: 1,
      //当前分页器展示的条数
      limit: 3,
      //总条数
      total: 0,
      list: [],
      dialogFormVisible: false,
      // 表单数据
      form: {
        tmName: "",
        logoUrl: "",
      },
      rules: {
        tmName: [
          { required: true, message: "请输入品牌名称", trigger: "blur" },
          { validator: validatetmName, trigger: "change" },
        ],
        logoUrl: [{ required: true, message: "请选择图片" }],
      },
    };
  },
  mounted() {
    this.getPageList();
  },
  methods: {
    async getPageList(pager = 1) {
      this.page = pager;
      const { page, limit } = this;
      let result = await this.$API.brand.reqGetPageList(page, limit);
      if (result.code === 200) {
        this.list = result.data.records;
        this.total = result.data.total;
      }
    },
    handleCurrentChange(limit) {
      this.limit = limit;
      this.getPageList();
    },
    openDialog() {
      this.dialogFormVisible = true;
      this.form.tmName = "";
      this.form.logoUrl = "";
    },
    cofirm() {
      const text = this.form.id ? "修改成功" : "保存成功";
      this.$refs["ruleForm"].validate(async (valid) => {
        if (valid) {
          let result = await this.$API.brand.BrandSaveUpdate(this.form);
          if (result.code === 200) {
            this.$message({
              messgae: text,
              type: "success",
            });
          }
          this.dialogFormVisible = false;
          this.getPageList(this.form.id ? this.page : 1);
        } else {
          return false;
        }
      });
    },
    //修改
    update(row) {
      this.dialogFormVisible = true;
      this.form = { ...row };
    },
    handleAvatarSuccess(res, file) {
      this.form.logoUrl = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    //删除
    deleteBrand(row) {
      this.$confirm(`确定要删除 ${row.tmName}`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let result = await this.$API.brand.reqDeleteBrand(row.id);
          if (result.code === 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getPageList(this.list > 1 ? this.page : this.page - 1);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
